package com.njust.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.njust.domain.dto.EquipmentDTO;
import com.njust.domain.dto.EquipmentPageQueryDTO;
import com.njust.domain.dto.RequestDTO;
import com.njust.domain.dto.SolutionDTO;
import com.njust.domain.po.*;
import com.njust.domain.vo.PageQueryVO;
import com.njust.mapper.EquipmentMapper;
import com.njust.mapper.EquipmentProcurementMapper;
import com.njust.mapper.SolutionMapper;
import com.njust.service.EquipmentService;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @Author: Grtiop
 * @Description: 设备相关
 * @DateTime: 2024/11/15 下午2:33
 **/
@Service
public class EquipmentServiceImpl implements EquipmentService {
    private static final Logger log = LoggerFactory.getLogger(EquipmentServiceImpl.class);
    @Autowired
    EquipmentMapper equipmentMapper;
    @Autowired
    SolutionMapper solutionMapper;
    @Autowired
    EquipmentProcurementMapper equipmentProcurementMapper;

    private final Object lock=new Object();

    public PageQueryVO pageQuery(EquipmentPageQueryDTO equipmentPageQueryDTO){
        PageHelper.startPage(equipmentPageQueryDTO.getPage(), equipmentPageQueryDTO.getPageSize());
        Page<Equipment> page = equipmentMapper.pageQuery(equipmentPageQueryDTO.getProject_id());
        long total = page.getTotal();
        List<Equipment> records = page.getResult();

        return new PageQueryVO(total, records);
    }

    public int addEquipment(EquipmentDTO equipmentDTO){
        synchronized (lock){
            // 先查询是否已存在该设备
            String equipmentName = equipmentDTO.getEquipment_name();
            int projectId = equipmentDTO.getProject_id();
            Equipment existEquipment = equipmentMapper.findByIdAndName(projectId,equipmentName);

            if(existEquipment == null){
                Equipment equipment = Equipment.builder()
                        .project_id(equipmentDTO.getProject_id())
                        .equipment_name(equipmentDTO.getEquipment_name())
                        .equipment_manufacturer(equipmentDTO.getEquipment_manufacturer())
                        .equipment_picture_link(equipmentDTO.getEquipment_picture_link())
                        .build();
                return equipmentMapper.insert(equipment);
            }
            else {
                return -1;
            }
        }

    }

    public int addSolution(SolutionDTO solutionDTO){
        synchronized (lock){
            // 先查询是否已存在该解决方案内容
            Solution existSolution = solutionMapper.findByText(solutionDTO.getSolution_text());

            if(existSolution == null){
                Solution solution = Solution.builder()
                        .equipment_id(solutionDTO.getEquipment_id())
                        .solution_text(solutionDTO.getSolution_text())
                        .build();
                return solutionMapper.insert(solution);
            }
            else {
                return -1;
            }
        }

    }

    public int updateSolution(SolutionDTO solutionDTO){
        Solution solution = Solution.builder()
                .solution_id(solutionDTO.getSolution_id())
                .equipment_id(solutionDTO.getEquipment_id())
                .solution_text(solutionDTO.getSolution_text())
                .build();
        return solutionMapper.updateById(solution);
    }

    public PageQueryVO searchSolution(int equipment_id){
        QueryWrapper<Solution> solutionQueryWrapper = new QueryWrapper<>();
        solutionQueryWrapper.eq("equipment_id",equipment_id);
        Long count = solutionMapper.selectCount(solutionQueryWrapper);
        List<Solution> solutionList = solutionMapper.selectList(solutionQueryWrapper);
        return new PageQueryVO(count, solutionList);
    }

    public int deleteSolution(int solution_id){
        return solutionMapper.deleteById(solution_id);
    }

    public int addRequest(RequestDTO requestDTO){
        QueryWrapper<EquipmentProcurement> equipmentProcurementQueryWrapper = new QueryWrapper<>();
        equipmentProcurementQueryWrapper.eq("uId",requestDTO.getUId());
        equipmentProcurementQueryWrapper.eq("solution_id",requestDTO.getSolution_id());
        equipmentProcurementQueryWrapper.isNotNull("status");
        EquipmentProcurement existEquipmentProcurement = equipmentProcurementMapper.selectOne(equipmentProcurementQueryWrapper);
        if(existEquipmentProcurement == null){
            EquipmentProcurement equipmentProcurement = EquipmentProcurement.builder()
                    .uId(requestDTO.getUId())
                    .equipment_id(requestDTO.getEquipment_id())
                    .status(requestDTO.getStatus())
                    .solution_id(requestDTO.getSolution_id())
                    .build();
            return equipmentProcurementMapper.insert(equipmentProcurement);
        }
        else{
            return -1;
        }
    }

    public int updateStatus(int equipment_procurement_id){
        UpdateWrapper<EquipmentProcurement> equipmentProcurementUpdateWrapper = new UpdateWrapper<>();
        equipmentProcurementUpdateWrapper.eq("equipment_procurement_id",equipment_procurement_id)
                .set("status",1);
        return equipmentProcurementMapper.update(null,equipmentProcurementUpdateWrapper);
    }

    public PageQueryVO pageQueryProcurement(int page, int pageSize){
        PageHelper.startPage(page,pageSize);
        Page<EquipmentProcurementPage> equipmentProcurementPages = equipmentProcurementMapper.findAll();
        long total = equipmentProcurementPages.getTotal();
        List<EquipmentProcurementPage> equipmentProcurementPageList = equipmentProcurementPages.getResult();
        return new PageQueryVO(total,equipmentProcurementPageList);
    }
    public void exportExcel(int project_id, HttpServletResponse response) {

        //准备表数据
        List<EquipmentProcurementPage> equipmentProcurementPageList = equipmentProcurementMapper.findByProjectId(project_id);
        try {
            // 读取Excel模板文件
            FileInputStream inputStream = new FileInputStream("src/main/resources/templates/清单.xlsx");
            Workbook workbook = new XSSFWorkbook(inputStream);
            inputStream.close();
            // 标记是否找到指定名称的Sheet
            boolean sheetFound = false;
            // 获取模板中的Sheet页数量
            int sheetCount = workbook.getNumberOfSheets();

            // 遍历所有Sheet，找到指定名称的Sheet并删除其他Sheet
            for (int i = 0; i < sheetCount; i++) {
                Sheet sheet = workbook.getSheetAt(i);
                if (sheet.getSheetName().equals("设备计划采购清单")) {
                    sheetFound = true;
                } else {
                    workbook.removeSheetAt(i);
                    i--;
                    sheetCount--;
                }
            }

            // 如果没有找到指定名称的Sheet，抛出异常
            if (!sheetFound) {
                throw new IllegalArgumentException("未在模板文件中找到名为'设备计划采购清单'的Sheet。");
            }


            // 获取模板中的Sheet页
            Sheet sheet = workbook.getSheet("设备计划采购清单");

            // 清空模板中的示例数据（从第二行开始，第一行是表头）
            int lastRowNum = sheet.getLastRowNum();
            for (int i = lastRowNum; i >= 1; i--) {
                Row row = sheet.getRow(i);
                if (row!= null) {
                    sheet.removeRow(row);
                }
            }

            // 定义日期格式
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");

            // 遍历查询到的数据库数据列表，将数据填充到Excel表格中
            int rowIndex = 1;
            for (EquipmentProcurementPage equipmentProcurementPage : equipmentProcurementPageList) {
                Row dataRow = sheet.createRow(rowIndex++);

                // 根据实体类属性将数据填充到对应的单元格
            dataRow.createCell(0).setCellValue(equipmentProcurementPage.getUName());
            dataRow.createCell(1).setCellValue(equipmentProcurementPage.getCategory());
            dataRow.createCell(2).setCellValue(equipmentProcurementPage.getProject_name());
            dataRow.createCell(3).setCellValue(equipmentProcurementPage.getProduct_name());
            dataRow.createCell(4).setCellValue(equipmentProcurementPage.getStandard_number());
            dataRow.createCell(5).setCellValue(equipmentProcurementPage.getEquipment_name());
            dataRow.createCell(6).setCellValue(equipmentProcurementPage.getStatus());
            }

            // 将填充好数据的Excel文件保存到本地
            ServletOutputStream outputStream=response.getOutputStream();
            String encodedFileName = URLEncoder.encode("设备计划采购清单.xlsx", "UTF-8");
            response.setHeader("Content-disposition","attachment;filename=\""+encodedFileName+"\"");
            workbook.write(outputStream);
            outputStream.close();
            workbook.close();
            log.info("数据已成功导出到Excel文件！");
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    @Transactional
    public void delete(int equipment_id) {
        //删除设备，要先删除对应的设备采购表和解决方案表
        QueryWrapper wrapper=new QueryWrapper<>();
        wrapper.eq("equipment_id",equipment_id);
        equipmentProcurementMapper.delete(wrapper);
        solutionMapper.delete(wrapper);
        equipmentMapper.deleteById(equipment_id);

    }
}
